/* eslint-disable react/jsx-key */
import React, { useState, useRef } from 'react';
import ReactDOM from 'react-dom';
import { Image, Alert, Tooltip, Modal, message, Button } from 'antd';
import AutoTable from '@/components/AutoTable';
import InitForm from '@/components/InitForm';
import { companydetail, activity, store } from '@/services/business';
import { search } from '@/services/basic';
import { classifydetail } from '@/services/basic';
import { payment } from '@/services/basic';
import { connect } from 'umi';
import { PlusOutlined } from '@ant-design/icons';
import ProDescriptions from '@ant-design/pro-descriptions';
import CompanyName from '@/components/CompanyName';

// type 类型有 table treeselect upload inputnumber datepicker daterange radio select textarea autoinput editor password input

let defaultFields = {
  payment_time: {
    value: null,
    type: 'datepicker',
    title: '收款日期',
    name: ['payment_time'],
    required: true,
    format: 'YYYY-MM-DD',
    showTime: false,
    disabledDate: null,
    disabledDateTime: null,
  },
  payment_id: {
    value: null,
    type: 'select',
    title: '收款方式',
    name: ['payment_id'],
    required: true,
    options: {
      database: payment,
      params: {},
    },
  },
  payment_price: {
    value: null,
    type: 'inputnumber',
    title: '收款金额',
    name: ['payment_price'],
    col: { span: 24 },
    required: true,
  },
  is_create_order: {
    value: null,
    type: 'radio',
    title: '是否创建业务单',
    name: ['is_create_order'],
    required: true,
    options: [
      {
        label: '是',
        value: true,
      },
      {
        label: '否',
        value: false,
      },
    ],
    linked: true,
  },
  price: {
    value: null,
    type: 'inputnumber',
    title: '续单金额',
    name: ['price'],
    required: true,
    belinked: {
      hides: [
        {
          name: 'is_create_order',
          equalvalue: [false],
          required: true,
        },
      ],
    },
  },
  service: {
    value: [],
    type: 'daterange',
    title: '续单服务时间',
    name: ['service'],
    required: true,
    col: { span: 24 },
    format: 'YYYY-MM-DD',
    belinked: {
      hides: [
        {
          name: 'is_create_order',
          equalvalue: [false],
          required: true,
        },
      ],
    },
  },
};

let options = [
    {
      id: 'accounting',
      name: '记账会计审核中',
    },
  ],
  valueEnum = {
    stalled: {
      text: '未开始',
    },
    accounting: {
      text: '记账会计审核中',
    },
    account_refuse: {
      text: '记账会计拒绝',
    },
    cancel: {
      text: '已取消',
    },
    completed: {
      text: '已完成',
    },
  },
  valueEnums = {
    cache: {
      text: '暂存',
    },
    stalled: {
      text: '未开始',
    },
    dispatching: {
      text: '会计调度中',
    },
    dispatch_refuse: {
      text: '会计调度拒绝',
    },
    accounting: {
      text: '记账会计审核中',
    },
    account_refuse: {
      text: '记账会计拒绝',
    },
    account_cache: {
      text: '记账会计暂存',
    },
    completed: {
      text: '已完成',
    },
  };

function Business(props) {
  const [vs, cvs] = useState(false), //表单显/隐
    [fields, cf] = useState(defaultFields),
    [iftype, ciftype] = useState({ curitem: {} }),
    [sd, csd] = useState(false);

  let actionRef = useRef(),
    ChildRef = null;
  function reload() {
    actionRef?.current?.reload();
    ChildRef?.onRefresh();
  }

  const columnscompany = [
    {
      title: '公司名称',
      width: 260,
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '公司法人',
      dataIndex: 'legal_person',
      key: 'legal_person',
      search: false,
      hideInTable: true,
    },
    {
      title: '公司地址',
      dataIndex: 'address',
      key: 'address',
      search: false,
      hideInTable: true,
    },
    {
      title: '统一社会信用代码',
      dataIndex: 'enterprise_credit_code',
      key: 'enterprise_credit_code',
      search: false,
      hideInTable: true,
    },
    {
      title: '公司营业执照',
      dataIndex: 'origin_url',
      key: 'origin_url',
      render: (_, row) => {
        return <Image width={32} height={32} style={{ padding: 2 }} src={row.origin_url} />;
      },
      hideInTable: true,
      search: false,
    },
    {
      title: '联系人',
      dataIndex: 'customer_name',
      key: 'customer_name',
      ellipsis: true,
    },
    {
      title: '联系人手机号',
      width: 120,
      dataIndex: 'customer_phone',
      key: 'customer_phone',
      render: (_, row) => (
        <Tooltip title={row.customer_phone}>
          <a href={`tel:${row.customer_phone}`} className="oneline">
            {row.customer_phone}
          </a>
        </Tooltip>
      ),
    },
    {
      title: '区域名称',
      dataIndex: 'area_name',
      key: 'area_name',
      search: false,
    },
    {
      title: '区域编码',
      dataIndex: 'area_code',
      key: 'area_code',
      search: false,
      hideInTable: true,
    },
    {
      title: '接单人',
      dataIndex: 'user_name',
      key: 'user_name',
      search: false,
      hideInTable: true,
    },
    {
      title: '促单人',
      dataIndex: 'promoter_user_name',
      key: 'promoter_user_name',
      search: false,
      hideInTable: true,
    },
    {
      title: '公司类型',
      dataIndex: 'classify_name',
      key: 'classify_name',
      search: false,
    },
    {
      title: '月收费',
      dataIndex: 'unit_price',
      key: 'unit_price',
      search: false,
    },
    {
      title: '活动',
      dataIndex: 'activity_content',
      key: 'activity_content',
      search: false,
      hideInTable: true,
    },
    {
      title: '续单',
      dataIndex: 'is_create_order',
      key: 'is_create_order',
      search: false,
      render: (_, row) => <span>{row.is_create_order ? '是' : '否'}</span>,
      hideInTable: true,
    },
    {
      title: '会计流程',
      dataIndex: 'is_accountant',
      key: 'is_accountant',
      search: false,
      render: (_, row) => <span>{row.is_accountant ? '是' : '否'}</span>,
      hideInTable: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      valueType: 'select',
      options: options,
      valueEnum: valueEnums,
      width: 120,
      render: (dom, row) => (
        <div
          style={{
            color: row?.status?.indexOf('refuse') != -1 ? 'red' : 'auto',
            cursor: 'pointer',
          }}
          onClick={() => {
            if (row?.status?.indexOf('refuse') != -1) {
              Modal.info({
                title: '拒绝原因',
                content: row.account_refuse_message,
                maskClosable: true,
              });
            }
          }}
        >
          {valueEnums[row.status].text}
        </div>
      ),
    },
    {
      title: '合同协议',
      dataIndex: 'contracts',
      key: 'contracts',
      search: false,
      render: (_, row) => {
        if (!row.contracts) {
          return (
            <Image
              width={32}
              height={32}
              style={{ padding: 2 }}
              src={require('@/assets/default.png')}
             />
          );
        } else {
          return row.contracts.map((it) => {
            return (
              <Image width={32} height={32} src={it.origin_url} style={{ padding: 2 }} />
            );
          });
        }
      },
      hideInTable: true,
    },
  ];

  const columns = [
    {
      title: '公司名称',
      width: 260,
      dataIndex: 'company_name',
      key: 'company_name',
      render: (_, row) => (
        <CompanyName
          row={{ ...row, name: row?.company_name ?? row.name, id: row?.company_id ?? row.id }}
          reload={reload}
        />
      ),
    },
    {
      title: '区域名称',
      dataIndex: 'area_name',
      key: 'area_name',
      search: false,
    },
    {
      title: '接单人',
      dataIndex: 'user_name',
      key: 'user_name',
      search: false,
    },
    {
      title: '促单人',
      dataIndex: 'promoter_user_name',
      key: 'promoter_user_name',
      search: false,
    },
    {
      title: '续单金额',
      dataIndex: 'price',
      key: 'price',
      search: false,
    },
    {
      title: '服务开始时间',
      dataIndex: 'service_start_time',
      key: 'service_start_time',
      search: false,
    },
    {
      title: '服务结束时间',
      dataIndex: 'service_end_time',
      key: 'service_end_time',
      search: false,
    },
    {
      title: '本次结算时间',
      dataIndex: 'settle_time',
      key: 'settle_time',
      search: false,
    },
    {
      title: '收款日期',
      dataIndex: 'payment_time',
      key: 'payment_time',
      search: false,
    },
    {
      title: '收款方式',
      dataIndex: 'payment_name',
      key: 'payment_name',
      search: false,
    },
    {
      title: '收款金额',
      dataIndex: 'payment_price',
      key: 'payment_price',
      search: false,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      valueType: 'select',
      options: options,
      valueEnum: valueEnum,
      width: 120,
      render: (_, row) => (
        <div
          className="oneline"
          style={{
            color: row?.status?.indexOf('refuse') != -1 ? 'red' : 'auto',
            cursor: 'pointer',
          }}
          onClick={() => {
            if (row?.status?.indexOf('refuse') != -1) {
              Modal.info({
                title: '拒绝原因',
                content: row.dispatch_refuse_message,
                maskClosable: true,
              });
            }
          }}
        >
          {valueEnum[row.status]?.text}
        </div>
      ),
    },
    {
      title: '操作',
      valueType: 'option',
      width: 100,
      render: (text, record, _, action) => [
        <a
          disabled={record.status == 'completed' || record.status == 'cancel'}
          onClick={() => {
            if (record.status == 'completed' || record.status == 'cancel') {
              return;
            }
            cvs(true);
            cf(() => {
              for (let i in defaultFields) {
                defaultFields[i].value = record[i] || null;
              }
              return { ...defaultFields };
            });
            ciftype({
              val: 'edit',
              title: '审批信息',
              id: record.id,
              curitem: record,
              type: record.status,
            });
          }}
        >
          审批
        </a>,
        <a
          style={{
            color: record.status == 'completed' || record.status == 'cancel' ? '#ddd' : '#f50',
          }}
          disabled={record.status == 'completed' || record.status == 'cancel'}
          onClick={() => {
            if (record.status == 'completed' || record.status == 'cancel') {
              return;
            }
            cvs(true);
            cf((fields) => {
              return {
                message: {
                  value: null,
                  type: 'textarea',
                  title: '拒绝理由',
                  name: ['message'],
                  required: false,
                  col: { span: 24 },
                },
              };
            });
            ciftype({
              val: 'refuse',
              title: '拒绝理由',
              curitem: record,
              id: record.id,
            });
          }}
        >
          拒绝
        </a>,
      ],
    },
  ];

  let saveData = (values) => {
    let { dispatch } = props;

    if (iftype.val == 'refuse') {
      dispatch({
        type: 'business/renewalrefuse',
        payload: { ...values, id: iftype.id },
      }).then((res) => {
        if (res.code == 0) {
          message.success('操作成功');
          reload();
          cvs(false);
        }
      });
    } else if (iftype.val == 'edit') {
      values = {
        ...values,
        service_start_time: values.service[0],
        service_end_time: values.service[1],
      };
      dispatch({
        type: 'business/renewalsubmits',
        payload: { ...values, id: iftype.id },
      }).then((res) => {
        if (res.code == 0) {
          message.success('操作成功');
          reload();
          cvs(false);
        }
      });
    }
  };

  return (
    <div className="pgcontainer">
      <AutoTable
        pagetitle={props.route.name} //页面标题
        columns={columns}
        actionRef={actionRef}
        onRef={(node) => (ChildRef = node)}
        path="/wbn-api/renewal_order"
        extraparams={{ type: 1 }}
        //withCard={false}
        //cardtitle = "name" //卡片标题
        //cardavatar = "img_url" //卡片头像
       />
      <Modal
        maskClosable={false}
        title={iftype.title}
        open={vs}
        onCancel={() => cvs(false)}
        footer={false}
        width={1400}
        destroyOnClose={true}
        style={{ top: 20 }}
      >
        {iftype.val == 'see' && iftype.curitem ? (
          <ProDescriptions
            title={`${iftype.curitem?.name}的详细信息`}
            columns={[...columnscompany]}
            column={{ xs: 1, sm: 1, md: 2, lg: 3, xl: 4, xxl: 5 }}
            dataSource={iftype.curitem}
          />
        ) : (
          <div>
            <Alert
              message="显示/隐藏详情"
              style={{ marginBottom: 20 }}
              showIcon
              type="info"
              action={
                <Button
                  size="small"
                  type="primary"
                  onClick={() => {
                    csd(!sd);
                  }}
                >
                  {!sd ? '显示' : '隐藏'}
                </Button>
              }
            />
            <div
              style={{
                backgroundColor: '#f9f9f9',
                padding: sd ? 12 : 0,
                paddingBottom: 0,
                borderRadius: 8,
                height: sd ? 'auto' : 0,
                transition: 'all 0.4s',
                overflow: 'hidden',
              }}
            >
              <ProDescriptions
                title={`${iftype.curitem?.company_name}的详细信息`}
                columns={[...columns]}
                column={{ xs: 1, sm: 1, md: 2, lg: 3, xl: 4, xxl: 5 }}
                dataSource={iftype.curitem}
              />
            </div>
            <InitForm
              fields={fields}
              submitData={(values) => {
                saveData(values);
              }}
              onChange={(changedValues, allValues) => {
                //联动操作
              }}
              submitting={props.loading.effects['business/renewalsubmits'] || !vs}
             />
          </div>
        )}
      </Modal>
    </div>
  );
}

export default connect(({ business, loading }) => ({
  business,
  loading,
}))(Business);
